import {Component, ElementRef, OnInit, Renderer2, ViewChild, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ToolsService} from "@shared/service/tools/tools.service";
import {Subject} from "rxjs/Subject";
import {FormControl} from "@angular/forms";
import {SaleService} from "@sale/sale.service";

import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {AuthService} from "@shared/service/auth/auth.service";
import {TrainSaleStudentRespVO} from "@interface/index";


@Component({
  selector: 'seed-customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class CustomerListComponent implements OnInit {
  @ViewChild('listHeader') listHeader: ElementRef;
  @ViewChild('dropDown') dropDown: ElementRef;
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  private ngUnsubscribe: Subject<any> = new Subject<any>();
  private params = {
    orgUserId: '',
    name: '',
    status: 0,
    page: 1,
    rows: 10
  };
  public salespersonStudentList: Array<TrainSaleStudentRespVO> = [];
  public searchInput: FormControl = new FormControl();
  public pageData = {
    isOpen: false, // 是否打开dropDown
    name: '',  // 搜索名字
    stateList: [{
      id: 0,
      title: '全部学员'
    }, {
      id: 1,
      title: '试课阶段'
    }, {
      id: 2,
      title: '试课结束'
    }, {
      id: 3,
      title: '跟进中'
    }, {
      id: 4,
      title: '流失学员'
    }, {
      id: 5,
      title: '正式学员'
    }],
    currentItem: null  // 初始化选中dataList
  };

  constructor(
    private toolsService: ToolsService,
    private service: SaleService,
    private route: ActivatedRoute,
    private router: Router,
    private render: Renderer2,
    private authService: AuthService
  ) {
    // 绑定valueChanges事件
    this.searchInput.valueChanges
      .debounceTime(300).distinctUntilChanged().subscribe(res => {
      this.params.name = res;
      this.salespersonStudentList = [];
      this.getSalespersonStudentList();
    });
  }

  /**
   * 获取客户列表信息
   */
  public getSalespersonStudentList() {
    if (!this.params.name) {
      delete this.params.name;
    }
    if (this.params.status === 0) {
      delete this.params.status;
    }
    this.service.getSalespersonStudentList(this.params).takeUntil(this.ngUnsubscribe).subscribe(res => {
      this.toolsService.hideLoading();
      if (this.checkResult(res) && res.data && res.data.list.length > 0) {
        this.params['page']++;
        this.infiniteScroll.complete();
        if (res.data.hasNextPage === false) {
          this.infiniteScroll.enable(false);
        }
        this.salespersonStudentList = [...this.salespersonStudentList, ...res.data.list];
      }
    });
  }

  /**
   * 打开下拉列表
   */
  public showDropDown() {
    const top = this.listHeader.nativeElement.getBoundingClientRect().top;
    const height = this.listHeader.nativeElement.getBoundingClientRect().height;
    this.render.setAttribute(this.dropDown.nativeElement, 'style', `top:${top + height}px`);
    this.pageData.isOpen = true;
  }

  /**
   * 关闭下拉列表
   */
  public closeDropDown($event) {
    $event.preventDefault();
    this.pageData.isOpen = false;
  }

  /**
   * 获取下拉选择
   */
  public onSelect(item) {
    this.params.status = item.id;
    this.pageData.currentItem = item;
    this.salespersonStudentList = [];
    this.params.page = 1;
    this.getSalespersonStudentList();
  }

  /**
   * 跳转客户详情
   */
  public jumpTo() {
    this.router.navigate(['/sale/custom']);
  }

  /**
   *检查返回状态
   */
  private checkResult(res) {
    if (res.result !== '0') {
      this.toolsService.showToast(res.msg);
    }
    return res.result === '0';
  }

  ngOnInit() {
    this.toolsService.showLoading();
    this.route.params.subscribe(params => {
      this.params.orgUserId = this.authService.getAuthOrgId();
      this.pageData.currentItem = this.pageData.stateList[0];
      this.getSalespersonStudentList();
    });
  }
}
